package com.hongqianping.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hongqianping.entity.BuserTable;
import com.hongqianping.entity.GoodsType;
import com.hongqianping.service.BuserTableService;
import com.hongqianping.service.GoodsTypeService;
import com.hongqianping.utils.MD5Util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import jakarta.servlet.http.HttpSession;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class UserController {

    @Autowired
    private BuserTableService buserTableService;

    @Autowired
    private GoodsTypeService goodsTypeService;

    @GetMapping("/register.html")
    public String registerPage(Model model) {
        List<GoodsType> goodsTypes = goodsTypeService.list();
        model.addAttribute("goodsTypes", goodsTypes);
        return "register"; // 解析到 src/main/resources/templates/user/register.html
    }

    @PostMapping("/register")
    public String register(@RequestParam("bemail") String bemail,
                           @RequestParam("bpwd") String bpwd,
                           Model model) {
        // 检查邮箱是否已存在
        LambdaQueryWrapper<BuserTable> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BuserTable::getBemail, bemail);
        BuserTable existingUser = buserTableService.getOne(queryWrapper);

        List<GoodsType> goodsTypes = goodsTypeService.list();
        model.addAttribute("goodsTypes", goodsTypes);

        if (existingUser != null) {
            model.addAttribute("error", "该邮箱已被注册！");
            return "register";
        }

        BuserTable newUser = new BuserTable();
        newUser.setBemail(bemail);
        newUser.setBpwd(MD5Util.md5(bpwd)); // 使用MD5对密码进行哈希

        boolean saved = buserTableService.save(newUser);
        if (saved) {
            model.addAttribute("message", "注册成功，请登录！");
            return "login"; // 注册成功后重定向到登录页面
        } else {
            model.addAttribute("error", "注册失败，请稍后再试！");
            return "register";
        }
    }

    @GetMapping("/login.html")
    public String loginPage(Model model) {
        List<GoodsType> goodsTypes = goodsTypeService.list();
        model.addAttribute("goodsTypes", goodsTypes);
        return "login"; // 解析到 src/main/resources/templates/user/login.html
    }

    @PostMapping("/login")
    public String login(@RequestParam("bemail") String bemail,
                        @RequestParam("bpwd") String bpwd,
                        @RequestParam(value = "verifyCode", required = false) String verifyCode, // 假设这是验证码输入
                        HttpSession session,
                        Model model) {
        // 获取导航栏所有商品类型
        List<GoodsType> goodsTypes = goodsTypeService.list();
        model.addAttribute("goodsTypes", goodsTypes);

        // 简单的验证码验证 (请替换为真实的验证码机制)
        // 为了简单起见，我们目前跳过实际的验证码生成和验证。
        // 如果您的login.html中有验证码，您需要生成并存储它在session中
        // String storedCaptcha = (String) session.getAttribute("verifyCode");
        // if (storedCaptcha == null || !storedCaptcha.equalsIgnoreCase(verifyCode)) {
        //     model.addAttribute("error", "验证码错误！");
        //     return "login";
        // }
        // session.removeAttribute("verifyCode"); // 验证后移除验证码

        // 用户认证
        LambdaQueryWrapper<BuserTable> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BuserTable::getBemail, bemail)
                    .eq(BuserTable::getBpwd, MD5Util.md5(bpwd)); // 对输入的密码进行MD5哈希后再进行比对
        BuserTable user = buserTableService.getOne(queryWrapper);

        if (user != null) {
            session.setAttribute("currentUser", user); // 在session中存储用户
            return "redirect:/index"; // 登录成功后重定向到首页
        } else {
            model.addAttribute("error", "邮箱或密码错误！");
            return "login";
        }
    }
    
    @GetMapping("/logout")
    public String logout(HttpSession session, Model model) {
        List<GoodsType> goodsTypes = goodsTypeService.list();
        model.addAttribute("goodsTypes", goodsTypes);
        session.invalidate(); // 使session失效
        return "redirect:/index"; // 重定向到首页
    }

    @GetMapping("/personalInfo")
    public String personalInfo(HttpSession session, Model model) {
        BuserTable currentUser = (BuserTable) session.getAttribute("currentUser");
        if (currentUser == null) {
            return "redirect:/login.html"; // 如果未登录，重定向到登录页面
        }
        List<GoodsType> goodsTypes = goodsTypeService.list();
        model.addAttribute("goodsTypes", goodsTypes);
        // 在实际应用中，可能会从数据库中获取更新的用户信息
        // 目前，我们使用的是session中的用户对象
        model.addAttribute("user", currentUser);
        return "personalInfo"; // 解析到 src/main/resources/templates/user/personalInfo.html
    }

    @PostMapping("/updatePersonalInfo")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> updatePersonalInfo(@RequestParam("newPassword") String newPassword,
                                                                    HttpSession session) {
        BuserTable currentUser = (BuserTable) session.getAttribute("currentUser");
        Map<String, Object> response = new HashMap<>();

        if (currentUser == null) {
            response.put("success", false);
            response.put("message", "请先登录！");
            return new ResponseEntity<>(response, HttpStatus.UNAUTHORIZED);
        }

        // 更新密码
        currentUser.setBpwd(MD5Util.md5(newPassword)); // 使用MD5哈希新密码
        boolean updated = buserTableService.updateById(currentUser);

        if (updated) {
            session.setAttribute("currentUser", currentUser); // 用新密码更新session
            response.put("success", true);
            response.put("message", "密码修改成功！");
            return new ResponseEntity<>(response, HttpStatus.OK);
        } else {
            response.put("success", false);
            response.put("message", "密码修改失败，请稍后再试！");
            return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
} 